<template>
  <Dialog v-model="dialogVisible" title="上传文件">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="80px"
    >
      <el-form-item label="选择分类" prop="dirId">
        <el-tree-select
          v-model="formData.dirId"
          :data="dirList"
          :props="defaultProps"
          check-strictly
          node-key="typeId"
          placeholder="请选择上传分类"
        /> </el-form-item
    ></el-form>
    <!--    accept=".jpg,.jpeg, .png, .gif, .mp4" -->
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      :action="uploadUrl"
      :auto-upload="false"
      :data="data"
      :disabled="formLoading"
      :multiple="true"
      :on-change="handleFileChange"
      :on-error="submitFormError"
      :on-exceed="handleExceed"
      :on-success="submitFormSuccess"
      :http-request="httpRequest"
      drag
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text"> 将文件拖到此处，或 <em>点击上传</em></div>
      <!-- <template #tip>
        <div class="el-upload__tip" style="color: red">
          提示：仅允许导入 jpg、jpeg、png、gif、mp4 格式文件！
        </div>
      </template> -->
    </el-upload>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitFileForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { useUpload } from '@/components/UploadFile/src/useUpload'
import { FormRules } from 'element-plus'

defineOptions({ name: 'InfraFileForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const fileList = ref([]) // 文件列表
const data = ref({ path: '', typeId: '' })
const uploadRef = ref()
const formData = ref({
  dirId: ''
})
const formRules = reactive<FormRules>({
  dirId: [{ required: true, message: '请选择上传分组', trigger: 'change' }]
})
const { uploadUrl, httpRequest } = useUpload()
/** 获得目录树 */
import * as FileApi from '@/api/infra/file'
import { handleTree } from '@/utils/tree'
const defaultProps = {
  children: 'children',
  label: 'typeName',
  value: 'typeId',
  isLeaf: 'leaf',
  multiple: false,
  emitPath: false // 用于 cascader 组件：在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
}
const dirList = ref<Tree[]>([]) // 树形结构
const getTree = async () => {
  const res = await FileApi.getSimpleDirList()
  dirList.value = []
  dirList.value.push(...handleTree(res, 'typeId'))
}
/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  getTree()
  resetForm()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 处理上传的文件发生变化 */
const handleFileChange = (file) => {
  data.value.path = file.name
}

/** 提交表单 */
const submitFileForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  if (fileList.value.length == 0) {
    message.error('请上传文件')
    return
  }
  data.value.typeId = formData.value.dirId
  unref(uploadRef)?.submit()
}

/** 文件上传成功处理 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitFormSuccess = () => {
  // 清理
  dialogVisible.value = false
  formLoading.value = false
  unref(uploadRef)?.clearFiles()
  // 提示成功，并刷新
  message.success(t('common.createSuccess'))
  emit('success')
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}

/** 重置表单 */
const formRef = ref()
const resetForm = () => {
  // 重置上传状态和文件
  formLoading.value = false
  formData.value = {
    dirId: ''
  }
  formRef.value?.resetFields()
  uploadRef.value?.clearFiles()
}

/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}
</script>
